package home

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"minititok/Entities"
	"minititok/Services"
	"minititok/utils"
	"net/http"
	"path/filepath"
	"strconv"
	"time"
)

func upLoadVideo(c *gin.Context) {

	user, _ := c.Get("user")
	currUser, _ := user.(*Entities.User)

	videoFile, err := c.FormFile("video")
	if err != nil {
		_ = c.Error(fmt.Errorf("文件上传失败:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessages": "文件错误"})
		return
	}
	title := c.PostForm("title")
	description := c.PostForm("description")
	if videoFile == nil {
		_ = c.Error(fmt.Errorf("文件为空"))
		c.JSON(http.StatusBadRequest, gin.H{"customMessages": "文件错误"})
		return
	}
	videoName := videoFile.Filename
	videoPath := filepath.Join("./staticSrc/staticVideo/", videoName)
	if Ferr := c.SaveUploadedFile(videoFile, videoPath); Ferr != nil {
		_ = c.Error(fmt.Errorf("文件保存失败:" + Ferr.Error() + ",路径:" + videoPath))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessages": "文件保存失败"})
		return
	}
	duration, coverName, err := utils.GetVideoDurationAndCover(videoPath, videoName)
	if err != nil {
		_ = c.Error(fmt.Errorf("视频解析失败:" + err.Error() + ",路径:" + videoPath))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessages": "封面与视频解析失败"})
		return
	}
	videoURL := fmt.Sprintf("http://localhost:8000/reVideo/%s", videoName)
	coverURL := fmt.Sprintf("http://localhost:8000/getCover/%s", coverName)
	newVideo := Entities.Video{
		Title:       title,
		Description: description,
		Duration:    duration,
		CoverURL:    coverURL,
		VideoURL:    videoURL,
		Author:      currUser.Username,
		CreateDate:  time.Now(),
	}
	if Serr := Services.CreateVideo(&newVideo); Serr != nil {
		_ = c.Error(fmt.Errorf("数据库错误,视频信息保存失败:" + Serr.Error()))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessages": "视频保存失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"customMessages": "上传成功"})
}

func deleteVideo(c *gin.Context) {
	user, _ := c.Get("user")
	currUser, ok := user.(*Entities.User)
	av := c.Param("av")
	orgAv := av
	av = av[2:]
	if !ok {
		_ = c.Error(fmt.Errorf("用户不存在,意外的删除"))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessage": "用户不存在"})
		return
	}
	intAv, _ := strconv.Atoi(av)
	video, Derr := Services.FindVideoByAV(int64(intAv))
	if Derr != nil {
		_ = c.Error(fmt.Errorf("视频不存在:" + Derr.Error() + ",AV号:" + orgAv))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessage": "视频不存在"})
		return
	}
	if video.Author != currUser.Username {
		_ = c.Error(fmt.Errorf("请求发起人不是视频主人,AV号:" + orgAv))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "没有权限"})
	}
	success, Fnerr := Services.DeleteByAV(int64(intAv))
	if success {
		c.JSON(http.StatusOK, gin.H{"customMessages": "删除成功"})
		return
	}
	_ = c.Error(fmt.Errorf("未知错误:%w", Fnerr))
	c.JSON(500, gin.H{"customMessages": "未知错误"})
}
